<?php
namespace Hilaoyu\LaravelExtend\Supports;
use Hilaoyu\Utils\UtilFile;
use Illuminate\Support\Carbon;

/**
 * Created by laoyu.
 * User: hilaoyu@qq.com
 * Date: 2019/4/29
 * Time: 14:17
 */



class FileQueue
{
    static public function make($sub_path=''){
        return new static($sub_path);
    }

    protected $queue_save_sub_path = '';

    public function __construct($sub_path='')
    {
        $this->queue_save_sub_path = $sub_path;
    }

    public function getSavePath($file_name=''){
        $paths = [
            '_laravel_extend_file_queue',
        ];
        if($this->queue_save_sub_path){
            $paths[] = $this->queue_save_sub_path;
        }
        if($file_name){
            $paths[] = $file_name;
        }

        return storage_path(implode(DIRECTORY_SEPARATOR,$paths));
    }


    public function put($data){
        $file_name = Carbon::now()->unix().'.'.uniqid('queue_');
        $save_path = $this->getSavePath($file_name);
        if(!UtilFile::checkDir(UtilFile::dirname($save_path))){
            return  false;
        }
        return file_put_contents($save_path,json_encode($data));
    }

    public function pop(){
        $dir = $this->getSavePath();
        $data = null;
        if ($handle = @opendir($dir)) {

            /* 这是正确地遍历目录方法 */
            while (false !== ($file = readdir($handle))) {
                if('.' == substr($file,0,1)){
                    continue;
                }
//                $copy_file = storage_path('_copy').DIRECTORY_SEPARATOR.$file;
                $file = $dir.DIRECTORY_SEPARATOR.$file;
                //dump($file);
                $data = @json_decode(file_get_contents($file),true);
//                @copy($file, $copy_file);
                @unlink($file);
                break;
            }
            closedir($handle);
        }

        return $data;
    }


}
